package com.zjuee.web.basic.file.controller;

import com.zjuee.base.bean.response.R;
import com.zjuee.base.constant.Common;
import com.zjuee.service.basic.file.service.FileService;
import com.zjuee.service.basic.file.vo.DownVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 文件 oss web 接口
 *
 * @author wuliang
 * @since 1.0
 */
@Slf4j
@RestController
@RequestMapping(path = Common.Service.ZJUEE_BASIC_FILE_URL_PREFIX, name = Common.Service.ZJUEE_BASIC_SERVICE_NAME)
public class FileController {

    @Resource
    private FileService fileService;

    /**
     * 文件上传接口
     *
     * @param modelName   存储模块名 - 英文表示比如plan
     * @param uploadFile 文件对象
     * @return           R对象
     */
    @PostMapping("/upload")
    public R<String> upload(@NotNull MultipartFile uploadFile, @NotBlank String modelName) {
        try {
            String path = fileService.upload(uploadFile, modelName);
            if (null != path) {
                return R.ok(path,"上传成功");
            }
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.fail();
    }

    /**
     * 文件上传接口 - 限制类型 + 可自定义文件名
     *
     * @param uploadFile 文件对象
     * @param limitType  文件限制类型
     * @param modelName  存储模块名 - 英文表示比如plan
     * @return           R对象
     */
    @PostMapping("/uploadLimitFile")
    public R<String> upload(@NotNull MultipartFile uploadFile, @NotBlank String limitType,
                            @NotBlank String modelName) {
        try {
            String path = fileService.upload(uploadFile, limitType, modelName);
            if (null != path) {
                return R.ok(path,"上传成功");
            }
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.fail();
    }

    /**
     * 文件下载
     *
     * @param downVo DownVo   文件路径
     */
    @PostMapping("/download")
    public void download(@RequestBody DownVo downVo) {

        fileService.download(downVo.getPath());
    }

    /**
     * 图片展示
     *
     * @param path     图片路径
     */
    @GetMapping(value = "/showImage")
    public void showImage(@RequestParam(value = "path") String path) {
        fileService.showImage(path);
    }
}
